<template>
  <div class="app-container">
    <el-card class="box-card">
      <div slot="header" class="clearfix">
        <el-row>
          <el-button type="success" @click="handleCreate"
          >&emsp;新增&emsp;
          </el-button
          >
          <el-button type="danger" @click="handleDeleteAll">批量删除</el-button>
        </el-row>
      </div>
      <div class="item">
        <el-table
          ref="dataList"
          v-loading="listLoading"
          :data="menuList"
          :tree-props="{ children: 'children', hasChildren: 'hasChildren' }"
          border
          row-key="id"
          style="width: 100%; margin-bottom: 20px"
          @selection-change="handleSelectionChange"
        >
          <el-table-column type="selection"></el-table-column>
          <el-table-column label="序号" prop="id"></el-table-column>
          <el-table-column label="名称" prop="name"></el-table-column>
          <el-table-column label="小图标" prop="icon">
            <template slot-scope="scope">
              <el-popover max-width="420" placement="right" trigger="hover">
                <img
                  :src="scope.row.icon"
                  alt=""
                  style="max-width: 200px; max-height: 200px"
                />
                <img
                  slot="reference"
                  :src="scope.row.icon"
                  alt=""
                  style="width: 50px"
                />
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="小图标(选中)" prop="icon_select">
            <template slot-scope="scope">
              <el-popover max-width="420" placement="right" trigger="hover">
                <img
                  :src="scope.row.icon_select"
                  alt=""
                  style="max-width: 200px; max-height: 200px"
                />
                <img
                  slot="reference"
                  :src="scope.row.icon_select"
                  alt=""
                  style="width: 50px"
                />
              </el-popover>
            </template>
          </el-table-column>
          <el-table-column label="可用房间类型" prop="room_type_name">
          </el-table-column>
          <el-table-column label="最低房主等级" prop="rank_id">
          </el-table-column>
          <el-table-column label="状态" prop="status">
            <template slot-scope="scope">
              <el-tag v-if="scope.row.status === 1" type="success">显示</el-tag>
              <el-tag v-if="scope.row.status === 0" type="danger">隐藏</el-tag>
            </template>
          </el-table-column>
          <el-table-column label="配置值" prop="config"></el-table-column>

          <el-table-column label="操作" width="180px">
            <template slot-scope="scope">
              <el-button
                icon="el-icon-edit"
                plain
                size="mini"
                type="primary"
                @click="handleUpdate(scope.row)"
              >编辑
              </el-button
              >
              <el-button
                icon="el-icon-delete"
                plain
                size="mini"
                type="danger"
                @click="handleDelete(scope.row)"
              >删除
              </el-button
              >
            </template>
          </el-table-column>
        </el-table>
        <!-- 分页 -->
        <cus-pagination
          :limit.sync="listQuery.perPage"
          :page.sync="listQuery.page"
          :total="total"
          @pagination="getList"
        />
      </div>
    </el-card>
    <!-- 删除弹框 -->
    <el-dialog
      :visible.sync="deleteDialogVisible"
      title="确定删除吗?"
      width="435px"
      @close="handleDialogClose('editRulesForm')"
    >
      <span style=""
      ><em style="font-style: normal; color: red">删除后不可恢复</em
      >，你还要继续吗？</span
      >
      <span slot="footer" class="dialog-footer">
        <el-button @click="deleteDialogVisible = false">取 消</el-button>
        <el-button type="primary" @click="confirmDelete">确 定</el-button>
      </span>
    </el-dialog>
    <!-- 新增编辑弹框 -->
    <el-dialog
      v-if="dialogFormVisible"
      v-dialogDrag
      :close-on-click-modal="false"
      :title="titleMap[dialogStatus]"
      :visible.sync="dialogFormVisible"
    >
      <el-form
        ref="dynamicValidateForm"
        :model="dynamicValidateForm"
        :rules="dynamicValidateRules"
        label-width="120px"
      >
        <el-form-item label="名称" prop="name">
          <el-input
            v-model="dynamicValidateForm.name"
            clearable
            placeholder="请输入配置标识"
          ></el-input>
        </el-form-item>
        <el-form-item label="小图标" prop="icon">
          <el-upload
            :http-request="customizeUpload"
            :on-success="handleSuccess"
            :show-file-list="false"
            action=""
            class="avatar-uploader"
          >
            <img
              v-if="dynamicValidateForm.icon"
              :src="dynamicValidateForm.icon"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="小图标(选中)" prop="icon_select">
          <el-upload
            :http-request="customizeUpload"
            :on-success="handleSuccess1"
            :show-file-list="false"
            action=""
            class="avatar-uploader"
          >
            <img
              v-if="dynamicValidateForm.icon_select"
              :src="dynamicValidateForm.icon_select"
              class="avatar"
            />
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
        </el-form-item>
        <el-form-item label="简介" prop="info">
          <el-input
            v-model="dynamicValidateForm.info"
            clearable
            placeholder="请输入简介"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item label="可用房间类型" prop="room_type">
          <el-select
            v-model="dynamicValidateForm.room_type"
            clearable
            filterable
            multiple
            placeholder="请选择可用房间类型"
          >
            <el-option
              v-for="item in typeOptions"
              :key="item.value"
              :label="item.label"
              :value="item.value"
            >
            </el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="参数设置" prop="config">
          <el-input
            v-model="dynamicValidateForm.config"
            placeholder="请输入参数"
            type="textarea"
          ></el-input>
        </el-form-item>
        <el-form-item label="最低房主等级" prop="rank_id">
          <el-input
            v-model.number="dynamicValidateForm.rank_id"
            clearable
            placeholder="请输入最低等级"
          ></el-input>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-radio v-model="dynamicValidateForm.status" :label="1"
          >显示
          </el-radio
          >
          <el-radio v-model="dynamicValidateForm.status" :label="0"
          >隐藏
          </el-radio
          >
        </el-form-item>
        <el-form-item>
          <el-button @click="dialogFormVisible = false">取 消</el-button>
          <el-button
            type="primary"
            @click="confirmSubmit('dynamicValidateForm')"
          >确 定
          </el-button
          >
        </el-form-item>
      </el-form>
    </el-dialog>
  </div>
</template>

<script>
import { deleteData, listData, listTypeData, postAddData, putEditData } from '@/api/room/soundEffect'

export default {
  data() {
    return {

      confirmBtn: false,

      editDetailFileList: [],
      editDetailFileList2: [],
      // 要修改的当前行的id
      row_id: 0,
      dynamicValidateRules: {
        name: [{ required: true, message: '请输入名称', trigger: 'blur' }],
        info: [{ required: true, message: '请输入简介', trigger: 'blur' }],
        room_type: [
          { required: true, message: '可用房间类型不能为空', trigger: 'blur' }
        ],
        config: [
          { required: true, message: '请输入参数设置', trigger: 'blur' }
        ],
        icon: [{ required: true, message: '请上传小图标', trigger: 'change' }],
        icon_select: [
          { required: true, message: '请上传小图标(选中)', trigger: 'change' }
        ],
        status: [{ required: true, message: '请选择状态', trigger: 'change' }]
      },
      dynamicValidateForm: {
        name: undefined,
        icon: undefined,
        icon_select: undefined,
        info: undefined,
        room_type: undefined,
        config: undefined,
        rank_id: undefined,
        status: 1
      },
      dialogFormVisible: false,
      deleteDialogVisible: false,
      dialogStatus: '',
      // dialog的头部信息
      titleMap: {
        update: '编辑',
        create: '添加'
      },
      listLoading: false,
      total: 0,
      menuList: [],
      listQuery: {
        page: 1,
        perpage: 10
      },
      typeOptions: [],
      groupOptions: [],
      // 勾选内容
      multipleSelection: [],
      // 要删除的内容的ids
      dataIds: ''
    }
  },
  created() {
    this.getGroupList()
    this.getList()
  },
  methods: {
    beforeAvatarUpload(file) {
      const isJPG =
        file.type === 'image/jpeg' ||
        file.type === 'image/png' ||
        file.type === 'image/webp' ||
        file.type === 'image/gif'
      const isLt2M = file.size / 1024 / 1024 < 2

      if (!isJPG) {
        this.$message.error('请上传JPG/PNG格式的图片!')
      }
      if (!isLt2M) {
        this.$message.error('上传图片大小不能超过 2MB!')
      }
      return isJPG && isLt2M
    },
    handleSuccess() {
      this.dynamicValidateForm.icon = this.ossLastImgUrl
    },
    handleSuccess1() {
      this.dynamicValidateForm.icon_select = this.ossLastImgUrl
    },
    handleChangePic(fileList) {
      if (fileList.length > 1) {
        fileList.splice(0, 1)
      }
    },

    getGroupList() {
      listTypeData().then(response => {
        for (let key in response.data) {
          this.typeOptions.push({ value: key, label: response.data[key] })
        }
      })
    },
    getList() {
      this.listLoading = true
      let urlData = '?'
      if (this.listQuery.page) {
        urlData = urlData + `page=${this.listQuery.page}&`
      }
      if (this.listQuery.perPage) {
        urlData = urlData + `perPage=${this.listQuery.perPage}`
      }
      // 发送异步请求
      // this.listLoading = false
      listData(urlData).then(response => {
        // response)
        this.menuList = response.data.list
        this.total = response.data.meta.total
        this.listLoading = false
        this.confirmBtn = false
      })
    },
    // 点击新增
    handleCreate() {
      this.resetForm('dynamicValidateForm')
      this.dialogStatus = 'create'
      this.dialogFormVisible = true
    },
    // 点击编辑
    handleUpdate(row) {
      this.row_id = row.id
      this.dynamicValidateForm.name = row.name
      this.dynamicValidateForm.icon = row.icon
      this.editDetailFileList = [{ url: row.icon }]
      this.dynamicValidateForm.icon_select = row.icon_select
      this.editDetailFileList2 = [{ url: row.icon_select }]
      this.dynamicValidateForm.info = row.info
      this.dynamicValidateForm.room_type = row.room_type.split(',')
      this.dynamicValidateForm.config = row.config
      this.dynamicValidateForm.rank_id = row.rank_id
      this.dynamicValidateForm.status = row.status
      this.dialogStatus = 'update'
      this.dialogFormVisible = true
    },
    resetForm(formName) {
      this.$nextTick(() => {
        if (this.$refs[formName] !== undefined) {
          this.$refs[formName].resetFields()
        }
      })
      this.dynamicValidateForm = {
        name: undefined,
        icon: undefined,
        icon_select: undefined,
        info: undefined,
        room_type: undefined,
        config: undefined,
        rank_id: undefined,
        status: 1
      }
      this.editDetailFileList = []
      this.editDetailFileList2 = []
    },
    confirmSubmit(formName) {
      if (this.confirmBtn) return
      this.$refs[formName].validate(valid => {
        if (valid) {
          this.confirmBtn = true
          if (this.dialogStatus === 'create') {
            let obj = JSON.parse(JSON.stringify(this.dynamicValidateForm))
            obj.room_type = obj.room_type.join(',')
            postAddData(obj).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              } else {
                this.confirmBtn = false
              }
            })
          } else {
            let obj = JSON.parse(JSON.stringify(this.dynamicValidateForm))
            obj.room_type = obj.room_type.join(',')
            putEditData(this.row_id, obj).then(response => {
              if (response.code === 200) {
                this.getList()
                this.dialogFormVisible = false
                this.$notify({
                  type: 'success',
                  message: '操作成功',
                  position: 'bottom-right',
                  showClose: false,
                  duration: 3000
                })
              } else {
                this.confirmBtn = false
              }
            })
          }
        } else {
          return false
        }
      })
    },
    // 勾选
    handleSelectionChange(val) {
      this.multipleSelection = val
    },
    // 点击单个删除
    handleDelete(row) {
      this.dataIds = { ids: `${row.id}` }
      this.deleteDialogVisible = true
    },
    // 点击批量删除
    handleDeleteAll() {
      if (this.multipleSelection.length === 0) {
        this.$message({
          message: '请先勾选要删除的内容',
          type: 'warning'
        })
        return
      } else if (this.multipleSelection.length !== 0) {
        let ids = ''
        for (let key in this.multipleSelection) {
          ids += `${this.multipleSelection[key].id},`
        }
        ids = ids.substring(0, ids.length - 1)
        this.dataIds = { ids: ids }
      }
      this.deleteDialogVisible = true
    },
    // 确定删除
    confirmDelete() {
      if (this.confirmBtn) return
      this.confirmBtn = true
      this.deleteDialogVisible = false
      deleteData(this.dataIds).then(response => {
        if (response.code === 200) {
          this.getList()
          this.deleteDialogVisible = false
          this.$notify({
            type: 'success',
            message: '操作成功',
            position: 'bottom-right',
            showClose: false,
            duration: 3000
          })
        } else {
          this.confirmBtn = false
        }
      })
    },
    // 监听dialog关闭时的处理事件
    handleDialogClose(formName) {
      if (this.$refs[formName]) {
        this.$refs[formName].clearValidate() // 清除整个表单的校验
      }
    }
  }
}
</script>

<style scoped>
[v-cloak] {
  display : none;
}

.clearfix:before,
.clearfix:after {
  display : table;
  content : "";
}

.clearfix:after {
  clear : both;
}

.box-card {
  width : 100%;
}

.demo-form-inline {
  float : right;
}

::v-deep.avatar-uploader .el-upload {
  border        : 1px dashed #d9d9d9;
  border-radius : 6px;
  cursor        : pointer;
  position      : relative;
  overflow      : hidden;
}

.avatar-uploader .el-upload:hover {
  border-color : #409eff;
}

.avatar-uploader-icon {
  font-size   : 28px;
  color       : #8c939d;
  width       : 100px;
  height      : 100px;
  line-height : 100px;
  text-align  : center;
}

.avatar {
  width   : 100px;
  height  : 100px;
  display : block;
}
</style>
